﻿using Datav.Design.Datas.Pocos;
using Datav.Design.Datas.Ticket;
using Datav.Design.IService;
using XCode;
using Zdap.Common;
using Zdap.Common.AutoMapper;
using Zdap.Common.Encrypt;
using Zdap.Common.Enums;
using Zdap.Common.Extensions;
using Zdap.Common.IdGenerate;
using Zdap.XCode;
using Zdap.XCode.Service;

namespace Datav.Design.Service
{
    /// <summary>
    ///
    /// </summary>
    public class ProjectUserService : BaseService<ProjectUser, ProjectUserModel>, IProjectUserService
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public override ValueTask<ResponseContext<long>> Save(ProjectUserModel dto, UserTicket user)
        {
            return base.Save(dto, user);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public async ValueTask<ResponseContext<UserTicket>> Login(LoginDto model, string ip)
        {
            var result = new ResponseContext<UserTicket>(CommonConstants.ErrorCode, null);
            var admissionTicket = model.UserName.Trim();
            var repo = await ProjectUser.FindAsync(ProjectUser._.MobilePhone == model.UserName & ProjectUser._.IsDelete == 0);
            if (repo == null)
            {
                return new ResponseContext<UserTicket> { Code = CommonConstants.ErrorCode, Msg = "登录失败,未找到该帐号！" };
            }
            if (repo != null)
            {
                //后六位
                //var passwork = model.Password;//GetLastStr(model.username, 6);
                var Password = model.Password.Md5();//repo.PasswordSalt
                if (repo.Password == Password)
                {
                    result.Code = CommonConstants.SuccessCode;
                    result.Data = new UserTicket()
                    {
                        Id = repo.Id,
                        MobilePhone = repo.MobilePhone,
                        RealName = repo.RealName,
                        LoginType = 0,
                        TenantId = repo.TenantId,
                        UserType = (UserTypeEnums)repo.UserType,
                        SchoolName = repo.SchoolName,
                        TaskId = repo.ProjectId,
                    };
                    return result;
                }
                else
                {
                    return new ResponseContext<UserTicket> { Code = CommonConstants.ErrorCode, Msg = "登陆失败，帐号或密码有误！" };
                }
            }
            return result;
        }


        /// <summary>
        /// 生成老师帐号
        /// </summary>
        /// <param name="caseId"></param>
        /// <param name="userId"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async ValueTask<ResponseContext<long>> Init(long caseId, long userId, UserTicket user)
        {
            var fssxUser = user.MapTo<ProjectUserModel>();
            fssxUser.ProjectId = caseId;
            fssxUser.Password = "zdap123".Md5();
            var uc = new UserCase
            {
                ProjectId = caseId,
                UserId = userId,
            };
            CommonService.SetCommonPropertyTenantId(uc, user);
            uc.Insert();
            return await this.Save(fssxUser, user);
        }

        ///// <summary>
        ///// 修改名称
        ///// </summary>
        ///// <param name="snapshot"></param>
        ///// <param name="user"></param>
        ///// <returns></returns>
        //public async ValueTask<ResponseContext<bool>> UpdatePositionName(PositionNameDto snapshot, UserTicket user)
        //{
        //    var rest = new ResponseContext<bool> { };
        //    var s = WorldDesignUser.FindById(snapshot.Id);

        //    if (string.IsNullOrEmpty(snapshot.PositionName))
        //    {
        //        return rest.SetError("名称不能为空！");
        //    }
        //    var count = await WorldDesignUser.FindCountAsync(WorldDesignUser._.Id == snapshot.Id & WorldDesignUser._.PositionName == snapshot.PositionName);

        //    if (count > 0)
        //    {
        //        return rest.SetError("组名不能相同！");
        //    }
        //    s.PositionName = snapshot.PositionName;
        //    s.Upsert(null, [WorldDesignUser._.PositionName]);
        //    rest.SetSuccess("修改成功！");
        //    return await Task.FromResult(rest);
        //}

        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        //public ValueTask<ResponseContext<bool>> SavesList(SavaListModel<WorldDesignUserModel> model, UserTicket currentUser)
        //{
        //    return base.Saves(model, currentUser);
        //}

        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="p"></param>
        ///// <returns></returns>
        //public Task<PageResponseContext<WorldDesignUserModel>> Search(Pager p)
        //{
        //    return base.Search(p);
        //}

        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="dto"></param>
        ///// <returns></returns>
        //protected override async ValueTask<ResponseContext<bool>> UpdateValidate(WorldDesignUserModel dto)
        //{
        //    //SetQuestionCategoryPolicy(dto.ProjectId);
        //    var result = new ResponseContext<bool>();
        //    if (string.IsNullOrWhiteSpace(dto.username))
        //    {
        //        return result.SetError($"帐号不能为空！");
        //    }
        //    var where = WorldDesignUser._.ProjectId == dto.ProjectId & WorldDesignUser._.TenantId == dto.TenantId & WorldDesignUser._.username == dto.username & WorldDesignUser._.IsDelete == 0;
        //    if (dto.Id > 0)
        //    {
        //        where &= WorldDesignUser._.Id != dto.Id;
        //    }
        //    var entity = await CommonService.FindBy<WorldDesignUser>(where);
        //    if (entity != null)
        //    {
        //        return result.SetError($"帐号“{dto.username}”已存在，不能重复！");
        //    }
        //    return result.SetSuccess(true);
        //}

        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="dto"></param>
        ///// <returns></returns>
        //protected override async ValueTask<ResponseContext<bool>> AddValidate(WorldDesignUserModel dto)
        //{
        //    var result = new ResponseContext<bool>();

        //    var repo = await WorldDesignUser.FindAsync(WorldDesignUser._.username == dto.username & WorldDesignUser._.IsDelete == 0);
        //    if (repo != null)
        //    {
        //        return await Task.FromResult(result.SetError("新增帐号已存在！"));
        //    }

        //    return await base.AddValidate(dto);
        //}



        ///// <summary>
        ///// 生成岗位帐号
        ///// </summary>
        ///// <param name="model"></param>
        ///// <param name="currentUser"></param>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //public async Task<ListResponseContext<WorldDesignUser>> PositionAccByProject(ExamGroupDto model, UserTicket currentUser)
        //{
        //    var result = new ListResponseContext<WorldDesignUser>();

        //    var verify = await IsVerify(model, currentUser);
        //    if (!verify.IsSuccess)
        //    {
        //        return result.SetError("案例创建人数已达限制数，请联系市场人员!");
        //    }

        //    var list = new List<WorldDesignUser>();
        //    var userCases = new List<UserCase>();
        //    var number = model.Number * 4;
        //    int digits = (int)Math.Ceiling(Math.Log10(number + 1));
        //    var index = 1;
        //    var groupIds = new string[] { "综合业务岗1 ", "融资业务岗", "投资业务岗", "综合业务岗2" };
        //    var remainingNumber = verify.Data;
        //    for (int i = 1; i <= model.Number; i++)
        //    {
        //        groupIds.ForEach((item, ind) =>
        //        {
        //            if (remainingNumber == 0)
        //            {
        //                //result.SetError("案例创建人数已达限制数，请联系市场人员!");
        //                return;
        //            }
        //            var userName = $"{model.Prefix}" + DateTime.Now.ToString("yyMMdd") + (i == 0 ? "" : $"{index.ToString("D" + digits)}");
        //            var where = WorldDesignUser._.TenantId == currentUser.TenantId & WorldDesignUser._.username == userName & WorldDesignUser._.IsDelete == 0;
        //            var entity = WorldDesignUser.FindCount(where);
        //            index++;
        //            if (entity >= 1)
        //            {
        //                return;
        //            }
        //            // 删除缓存
        //            var itemUser = currentUser.MapTo<WorldDesignUser>();
        //            itemUser.Id = IdWorker.NextId();
        //            itemUser.UserType = (int)UserTypeEnums.Student;
        //            itemUser.username = userName;
        //            itemUser.RealName = userName;
        //            itemUser.Password = string.IsNullOrEmpty(model.Password) ? "zdap123".Md5() : model.Password.Md5();
        //            itemUser.PositionName = "";
        //            itemUser.ProjectId = model.CaseId;
        //            itemUser.PasswordSalt = string.IsNullOrEmpty(model.Password) ? "zdap123" : model.Password;
        //            CommonService.SetCommonPropertyTenantId(itemUser, currentUser);
        //            list.Add(itemUser);
        //            var uc = new UserCase
        //            {
        //                Id = IdWorker.NextId(),
        //                ProjectId = model.CaseId,
        //                UserId = itemUser.Id
        //            };
        //            CommonService.SetCommonPropertyTenantId(uc, currentUser);
        //            userCases.Add(uc);
        //            remainingNumber--;
        //        });
        //    }

        //    using (var tran1 = WorldDesignUser.Meta.CreateTrans())
        //    {
        //        list.Insert();
        //        userCases.Insert();
        //        tran1.Commit();
        //    }

        //    //执行统计
        //    await IsVerify(model, currentUser);

        //    result.Data = list;

        //    return await Task.FromResult(result);
        //}

        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="model"></param>
        ///// <param name="currentUser"></param>
        ///// <returns></returns>
        //private async Task<ResponseContext<long>> IsVerify(ExamGroupDto model, UserTicket currentUser)
        //{
        //    var result = new ResponseContext<long>();
        //    var limit = await LimitConfig.FindAsync(LimitConfig._.TenantId == currentUser.TenantId & LimitConfig._.UserId == currentUser.Id & LimitConfig._.IsDelete == 0);
        //    long usercount = await WorldDesignUser.FindCountAsync(WorldDesignUser._.TenantId == currentUser.TenantId & WorldDesignUser._.UserType == 1
        //        & Project._.CreateBy == currentUser.Id
        //        & WorldDesignUser._.IsDelete == 0);
        //    // &WorldDesignUser._.ProjectId == model.CaseId
        //    if (limit != null)
        //    {
        //        limit.RemainingNumber = (int)(limit.LimitAccountNumber - usercount);
        //        if (limit.RemainingNumber < 0)
        //        {
        //            limit.RemainingNumber = 0;
        //        }
        //        limit.Update();
        //    }
        //    if (limit.RemainingNumber == 0)
        //    {
        //        return result.SetError($"案例剩余帐号数为{limit.RemainingNumber}，请联系市场人员!");
        //    }

        //    return result.SetSuccess(limit.RemainingNumber);
        //}

        ///// <summary>
        ///// 删除账号更新
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="user"></param>
        ///// <returns></returns>
        //public override async ValueTask<ResponseContext<bool>> Delete(long id, UserTicket user)
        //{
        //    var i = await base.Delete(id, user);
        //    await ExecuteStatistics(id, user);
        //    return await Task.FromResult(i);
        //}

        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="currentUser"></param>
        ///// <returns></returns>
        //private static async Task ExecuteStatistics(long id, UserTicket currentUser)
        //{
        //    long usercount = await WorldDesignUser.FindCountAsync(WorldDesignUser._.TenantId == currentUser.TenantId & WorldDesignUser._.UserType == 1 & Project._.CreateBy == currentUser.Id & WorldDesignUser._.IsDelete == 0);
        //    var limit = await LimitConfig.FindAsync(LimitConfig._.TenantId == currentUser.TenantId & LimitConfig._.UserId == currentUser.Id & LimitConfig._.IsDelete == 0);
        //    if (limit != null)
        //    {
        //        limit.RemainingNumber = (int)(limit.LimitAccountNumber - usercount);
        //        limit.Update();
        //    }
        //}



        ///// <summary>
        /////
        ///// </summary>
        //private const string RedisKey = "SLRH_Captcha_{0}";

        ///// <summary>
        ///// 获取图像验证码数据
        ///// </summary>
        ///// <param name="type">验证码类型（0-普通验证码 1-算数计算验证码）</param>
        ///// <param name="width">验证码图片宽度</param>
        ///// <param name="height">验证码图片高度</param>
        ///// <param name="length">验证码字符个数</param>
        ///// <param name="pid">验证码唯一ID（由服务端雪花算法生成并返回，验证的时候传回服务端）</param>
        //public CaptchaResult GetVerifyCode(CaptchaType type = CaptchaType.Normal, int width = 120, int height = 30, int length = 4, long pid = 0)
        //{
        //    if (pid > 0)
        //    {
        //        var oldKey = GetRedisKey(pid);
        //        RedisHelper.Del(oldKey);
        //    }
        //    var result = CaptchaUtility.GetVerifyCode(width, height, length, captchaType: type);
        //    result.Id = IdWorker.NextId();
        //    RedisHelper.Set(GetRedisKey(result.Id), result.CaptchaValue, 3 * 60);
        //    return result;
        //}

        ///// <summary>
        ///// 获取存储的Redis键
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //private static string GetRedisKey(long id)
        //{
        //    return string.Format(RedisKey, id);
        //}
    }
}